<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>人脸识别Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/work_main/layui/css/layui.css">
    
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="/work_main/layui/layui.js"></script>
</head>
<style>
    video, canvas {
        margin-left: -120px;
        margin-top: 120px;
        position: absolute;
    }
</style>
<script>
  //注意：选项卡 依赖 element 模块，否则无法进行功能性操作
  layui.use(['layer', 'jquery', 'form', 'element'], function () {
    var layer = layui.layer, $ = layui.jquery, form = layui.form;
    form.render();
  });
  $(function () {
    var token = getCookie("token");
    if (token != null) {
      // $("#showlogin").hide();
    }else{
      $("#showMine").hide();
    }
   /* $("#butlogin").click(function () {
      $("#showlogin").show();
    })*/
  })

  function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
      return unescape(arr[2]);
    else
      return null;
  }

  var _index;
</script>
<body>
<div class="layui-layout layui-layout-admin">
    <!--<button id="butlogin" class="layui-btn layui-btn-normal">显示登陆</button>
    <div id="showlogin" class="layui-form layui-form-pane">
        <form action="/work_main/authentication" method="post">
            <div class="layui-form-item">
                <label class="layui-form-label">账号：</label>
                <div class="layui-input-block"><input class="layui-input" name="account"></div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码：</label>
                <div class="layui-input-block"><input class="layui-input" type="password" name="password"></div>
            </div>
            <div class="layui-input-block"><input class="layui-btn layui-btn-normal" type="submit"></div>
        </form>
    </div>-->
    <div class="layui-tab">
        <ul class="layui-tab-title">
            <li class="layui-this">人脸注册</li>
            <li>人脸搜索</li>
            <li onclick="mineFace()" id="showMine">我的人脸</li>
        </ul>
        <div style="position: absolute;margin-left: 40px">
            <style type="text/css">
                table.hovertable {
                    font-family: verdana, arial, sans-serif;
                    font-size: 11px;
                    color: #333333;
                    border-width: 1px;
                    border-color: #999999;
                    border-collapse: collapse;
                }

                table.hovertable th {
                    background-color: #c3dde0;
                    border-width: 1px;
                    padding: 8px;
                    border-style: solid;
                    border-color: #a9c6c9;
                }

                table.hovertable tr {
                    background-color: #d4e3e5;
                }

                table.hovertable td {
                    border-width: 1px;
                    padding: 8px;
                    border-style: solid;
                    border-color: #a9c6c9;
                }
            </style>
        </div>
        <div class="layui-tab-content" style="">
            <!--人脸注册-->
            <div class="layui-tab-item layui-show">
                <div class="layui-row">
                    <div class="layui-col-xs7 layui-col-md-offset3" align="center">
                        
                        <div id="mainDiv">
                        </div>
                        <div  style="margin-top: 30px;">
                            <div class="layui-btn-container layui-btn-group">
                                        <button title="摄像头注册" value="摄像头注册" onclick="getMedia()"
                                                class="layui-btn">
                                            摄像头注册
                                        </button>
                                        <button
                                            class="layui-btn"
                                            onclick="imageRecog()">照片注册
                                        </button>
                            </div>
                            <div class="layui-btn-container">
                                        <button  onclick="takePhoto()"
                                                class="layui-btn layui-btn-normal">
                                            提交
                                        </button>
                            </div>
                        </div>
                        <div style="float: right">
                        
                        </div>
                    </div>
                
                
                </div>
                <script>
                  /**
                   * 压缩图片
                   * @param img 被压缩的img对象
                   * @param type 压缩后转换的文件类型
                   */
                  function compressImg(img, type) {
                    return new Promise((resolve, reject) => {
                      const canvas = document.createElement('canvas')
                      const context = canvas.getContext('2d')
                      const {width: originWidth, height: originHeight} = img
                      // 最大尺寸限制
                      const maxWidth = 1000
                      const maxHeight = 1000
                      // 目标尺寸
                      let targetWidth = originWidth
                      let targetHeight = originHeight
                      if (originWidth > maxWidth || originHeight > maxHeight) {
                        if (originWidth / originHeight > 1) {
                          // 宽图片
                          targetWidth = maxWidth
                          targetHeight = Math.round(maxWidth * (originHeight / originWidth))
                        } else {
                          // 高图片
                          targetHeight = maxHeight
                          targetWidth = Math.round(maxHeight * (originWidth / originHeight))
                        }
                      }
                      canvas.width = targetWidth
                      canvas.height = targetHeight
                      context.clearRect(0, 0, targetWidth, targetHeight)
                      // 图片绘制
                      context.drawImage(img, 0, 0, targetWidth, targetHeight)
                      resolve(canvas.toDataURL('image/png', 0.7))
                    })
                  }

                  // 压缩前将file转换成img对象
                  function readImg(file) {
                    return new Promise((resolve, reject) => {
                      const img = new Image()
                      const reader = new FileReader()
                      reader.onload = function (e) {
                        img.src = e.target.result
                      }
                      reader.onerror = function (e) {
                        reject(e)
                      }
                      reader.readAsDataURL(file)
                      img.onload = function () {
                        resolve(img)
                      }
                      img.onerror = function (e) {
                        reject(e)
                      }
                    })
                  }

                  function getMedia() {
                    $("#mainDiv").empty();
                    let camera = "<input type=\"file\" name='fffpp' id='fffpp' multiple='multiple' accept=\"image/*\" capture=\"camera\">";
                    $("#mainDiv").append(camera);
                    $("#fffpp").hide();
                    $("#fffpp").trigger('click');
                  }

                  //拍照事件
                  async function takePhoto() {
                    //敲黑板
                    _index = layer.load(1, {
                      content: "<div style='margin-left:-2px;padding-top:44px;width:120px;color:#FFF;'>正在上传<span id='loadProgress' ></span></div>",
                      shade: [0.5, '#000']
                    });
                    let src = $('#price').attr("src");
                    if (src != null) {
                      var file = $("#fffpp")[0].files[0];
                      var img = await readImg(file);
                      const base64 = await compressImg(img, file.type)
                      var formData = new FormData();
                      formData.append("file", base64);
                      $.ajax({
                        type: "post",
                        url: "/work_main/api/face_add",
                        data: formData,
                        contentType: false,
                        processData: false,
                        async: false,
                        complete: function () {
                          layer.close(_index);
                        },
                        success: function (res) {
                          layer.close(_index);
                          if (res.code == 1) {
                            layer.msg("添加成功", {icon: 6,time: 3000})
                          } else {
                            layer.msg(res.msg, {icon: 2,time: 3000})
                          }
                        },
                        error: function (error) {
                          layer.close(_index);
                          layer.msg(JSON.stringify(error))
                        }
                      });
                    } else {
                      var file1 = $("#file0")[0].files[0];
                      var img1 = await readImg(file1);
                      const base64 = await compressImg(img1, file1.type)
                      var formData1 = new FormData();
                      formData1.append("file", base64);
                      $.ajax({
                        type: "post",
                        url: "/work_main/api/face_add",
                        data: formData1,
                        contentType: false,
                        processData: false,
                        async: false,
                        complete: function () {
                          layer.close(_index);
                        },
                        success: function (res) {
                          console.log(res)
                          layer.close(_index);
                          if (res.code == 1) {
                            layer.msg("添加成功", {icon: 6,time: 3000})
                            location.reload();
                          } else {
                            layer.msg(res.msg, {icon: 2,time: 3000})
                          }
                        },
                        error: function (error) {
                          layer.close(_index);
                          layer.msg(JSON.stringify(error))
                        }
                      });
                    }

                  }

                  function imageRecog() {
                    let imageInput = " <h2>点击图片区域上传文件</h2><input style='display: none' type='file'  name='file0' id='file0' multiple='multiple' /><br><img src='/work_main/images/shibie.jpg' id='img0' onclick='toChooseFile()' style='width: 30rem;height: 25rem;'>";
                    $("#mainDiv").empty();
                    $("#mainDiv").append(imageInput);
                  }

                  function toChooseFile() {
                    $("#file0").trigger('click');
                  }

                  $(document).on("change", "#fffpp", function () {
                    var objUrl = getObjectURL(this.files[0]);//获取文件信息
                    if (objUrl) {
                      let imageInput = "<img src='" + objUrl + "' id='price' style='width: 30rem;height: 25rem;'>";
                      $("#mainDiv").append(imageInput);
                    }
                  });

                  $(document).on("change", "#file0", function () {
                    var objUrl = getObjectURL(this.files[0]);//获取文件信息
                    if (objUrl) {
                      $("#img0").attr("src", objUrl);
                    }
                  });

                  function getObjectURL(file) {
                    var url = null;
                    if (window.createObjectURL != undefined) {
                      url = window.createObjectURL(file);
                    } else if (window.URL != undefined) { // mozilla(firefox)
                      url = window.URL.createObjectURL(file);
                    } else if (window.webkitURL != undefined) { // webkit or chrome
                      url = window.webkitURL.createObjectURL(file);
                    }
                    return url;
                  }
                
                
                </script>
            </div>
            <!--人脸搜索-->
            <div class="layui-tab-item">
                <div class="layui-row">
                    <div class="layui-col-xs7 layui-col-md-offset3" align="center">
                        
                        <div id="regcoDiv">
                        
                        </div>
                        <div  style="margin-top: 30px;">
                            <div class="layui-btn-container layui-btn-group">
                                        <button title="人脸识别" value="人脸识别" onclick="getMedia2()"
                                                class="layui-btn">
                                            摄像头识别
                                        </button>
                                        <button
                                            class="layui-btn"
                                            onclick="imageTo()">照片识别
                                        </button>
                            </div>
                            <div class="layui-btn-container">
                                        <button  onclick="chooseFileChangeComp()"
                                                class="layui-btn layui-btn-normal">
                                            提交
                                        </button>
                            </div>
                        
                        </div>
                        <div>
                            <img id="imageDivComp"/>
                        </div>
                        
                        <div id="resData"></div>
                    </div>
                
                </div>
                <script>

                  function chooseFile() {
                    $("#file1").trigger('click');
                  }

                  function imageTo() {
                    $("#regcoDiv").empty();
                    let imageInput = "<h2>点击图片区域上传文件</h2><input style='display: none' type='file' name='file1' id='file1' multiple='multiple' /><br><img src='/work_main/images/shibie.jpg' onclick='chooseFile()' id='img1' style='width: 30rem;height: 25rem;'>";
                    $("#regcoDiv").append(imageInput);

                  }

                  $(document).on("change", "#file1", function () {
                    var objUrl = getObjectURL(this.files[0]);//获取文件信息
                    console.log("objUrl = " + objUrl);
                    if (objUrl) {
                      $("#img1").attr("src", objUrl);
                    }
                  });

                  function getObjectURL(file) {
                    var url = null;
                    if (window.createObjectURL != undefined) {
                      url = window.createObjectURL(file);
                    } else if (window.URL != undefined) { // mozilla(firefox)
                      url = window.URL.createObjectURL(file);
                    } else if (window.webkitURL != undefined) { // webkit or chrome
                      url = window.webkitURL.createObjectURL(file);
                    }
                    return url;
                  }

                  $("#imageDivComp").click(function () {
                    $("#chooseFileComp").click();

                  });

                  function getMedia2() {
                    window.location.href = "/work_main/face.html"
                  }

                  function chooseFileChangeComp() {
                    var file = $("#file1")[0].files[0];
                    if (file == undefined) {
                      layer.msg("请选择有人脸的图片进行识别", {icon: 2,time: 3000})
                      return;
                    }
                    //敲黑板
                    _index = layer.load(1, {
                      content: "<div style='margin-left:-2px;padding-top:44px;width:120px;color:#FFF;'>正在查询<span id='loadProgress'></span></div>",
                      shade: [0.5, '#000']
                    });
                    var formData = new FormData();
                    var reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = function () {
                      var base64 = reader.result;
                      formData.append("file", base64);
                      $.ajax({
                        type: "post",
                        url: "/work_main/api/face_search",
                        data: formData,
                        contentType: false,
                        processData: false,
                        async: false,
                        success: function (text) {
                          layer.close(_index);
                          var res = JSON.stringify(text)
                          if (text.code === 1) {
                            if (text.data == null) {
                              $("#resData").html("人脸不正确")
                              return;
                            }
                            var name = text.data.name;
                            var htmlData = "姓名：" + name
                            var similar = text.data.similarValue;
                            htmlData += "相似度：" + similar + "%";
                            var age = text.data.age;
                            htmlData += "年龄：" + age
                            var gender = text.data.gender;
                            htmlData += "性别：" + gender
                            $("#resData").html(htmlData);
                          } else {
                            $("#resData").html("人脸不匹配")
                          }
                        },
                        error: function (error) {
                          layer.close(_index);
                          $("#resData").html(JSON.stringify(error))
                        }
                      });
                    }
                  }
                </script>
            </div>
            <div class="layui-tab-item">
                <div class="layui-row">
                    <div class="layui-col-xs7 layui-col-md-offset3" align="center">
        
                        <div id="mineDev">
        
                        </div>
                    </div>
                </div>
                <script>
                    async function mineFace(){
                      $("#mineDev").empty();
                      const token = getCookie("token");
                      if (token != null) {
                        $.ajax({
                          type: "get",
                          url: "/work_main/api/get_mine_face",
                          contentType: false,
                          processData: false,
                          async: false,
                          success: function (text) {
                            if (text.code==1&&text.data != null) {
                              let mineInput = "<img src='"+text.data+"' style='width: 320px;height: 240px;'/> <button onclick='deleteFace()' style=\"margin-top:10px\" type=\"button\" class=\"layui-btn\" title='删除'><i class=\"layui-icon\"></i></buttonstyle>";
                              $("#mineDev").append(mineInput);
                            }
                          },
                          error: function (error) {
                          }
                        });
                       
                      }
                    }
                    function deleteFace(){
                      $("#mineDev").empty();
                      $.ajax({
                        type: "delete",
                        url: "/work_main/api/delete_mine_face",
                        contentType: false,
                        processData: false,
                        async: false,
                        success: function (text) {
                          layer.msg("删除成功", {icon: 6,time: 3000})
                        },
                        error: function (error) {
                        }
                      });
                    }
                </script>
            </div>
        </div>
    </div>
</div>
</body>
</html>